package _1_5_type_convert;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import org.junit.Test;

/**
 * Created by bpzj on 2019-01-14.
 */
public class BeanToJsonString {

    public static void main(String[] args) throws JsonProcessingException {
        JavaBean bean = new JavaBean("yamin", "million");

        // 使用 ObjectMapper
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(bean);
        System.out.println(json);

        //
        ObjectWriter objectWriter = new ObjectMapper().writer().withDefaultPrettyPrinter();
        String json2 = objectWriter.writeValueAsString(bean);
        System.out.println(json2);
    }

    @Test
    public void useFastJson() {
        // 默认会去掉空值的字段
        JavaBean bean = new JavaBean("", "million");
        bean.setName(null);
        String json = JSON.toJSONString(bean);
        System.out.println(json);

        // 保留空值字段，但是字段值是 null
        String andNullJson = JSON.toJSONString(bean, SerializerFeature.WriteMapNullValue);
        System.out.println(andNullJson);
    }

}
